package com.summer.framework.common.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.framework.common.distributed.lock.DistributedReadWriteLock;
import com.summer.framework.common.exception.NotFoundException;
import com.summer.framework.common.mapper.MyBaseMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @auther: 杨杰
 * @date: 2018/11/12 14:11
 * @description:
 */
@Service
@Slf4j
public abstract class BaseServiceImpl<M extends MyBaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T> {

    @Autowired
    protected RedissonClient redisson;

    @Autowired
    protected DistributedReadWriteLock distributedReadWriteLock;

    @Autowired
    protected M baseMapper;

    @Override
    public T getById(Serializable id) {
        return Optional.ofNullable(baseMapper
                .selectById(id))
                .orElseThrow(() -> new NotFoundException("无法通过id找到信息"));
    }

    @Override
    public boolean isExist(String cloumName, Object value) {
        return count(new QueryWrapper<T>().eq(cloumName, value)) > 0;
    }

    @Override
    public boolean isNotExist(String cloumName, Object value) {
        return !isExist(cloumName, value);
    }

    @Override
    public IPage<T> page(Integer current, Integer size, T t) {
        QueryWrapper query = new QueryWrapper<T>(t);
        Page<T> page = new Page<>(current, size);
        return super.page(page, query);
    }

    @Override
    public boolean deleteByIds(String[] ids) {
        return removeByIds(Arrays.stream(ids).collect(Collectors.toList()));
    }

}

